package com.hxd.otc.module.order.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hxd.otc.R;
import com.hxd.otc.base.LazyFragment;
import com.hxd.otc.event.Event;
import com.hxd.otc.module.order.activity.AdBuyOrderDetailActivity;
import com.hxd.otc.module.order.activity.AdSaleOrderDetailActivity;
import com.hxd.otc.module.order.activity.BuyOrderDetailActivity;
import com.hxd.otc.module.order.activity.OrderFinishedActivity;
import com.hxd.otc.module.order.activity.SaleOrderDetailActivity;
import com.hxd.otc.module.order.adapter.AllOrderAdapter;
import com.hxd.otc.module.order.bean.AllOrderBean;
import com.hxd.otc.module.order.contract.AllOrderContract;
import com.hxd.otc.module.order.presenter.AllOrderPresenter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;

/**
 * 作  者 :  zjl
 * 时  间 :  2018/6/5 17:19
 * 描  述 :  ${所有订单页面}
 */
public class AllOrderFragment extends LazyFragment<AllOrderPresenter> implements AllOrderContract.View {

    private static AllOrderFragment instance = null;

    public static final String ORDER_ID = "orderSn";
    public static final String ORDERINFO = "orderInfo";

    @BindView(R.id.refreshLayout)
    @NonNull
    SmartRefreshLayout mRefreshLayout;

    @BindView(R.id.recyclerView)
    @NonNull
    RecyclerView recyclerView;

    View errorView;

    View notDataView;

    TextView tvRefresh;

    @NonNull
    AllOrderAdapter adapter;

    private boolean isRefresh;
    private int currentPage = 1;//当前页
    private int rows = 15;//每页显示条数

    private int status = -1;

    boolean isFrist = true;
    boolean isNormalOrder;

    @Override
    protected void initData() {
        isNormalOrder = getArguments().getBoolean("isNor");
        status = getArguments().getInt(OrderFragment.ORDER_STATUES, -1);
        initAdapter();
        mRefreshLayout.autoRefresh(0, 10, 1);
        registerEventBus();

    }

    public static final int REQUEST_CODE_UPDATE_INFO = 123;

    private void initAdapter() {
        if (adapter == null) {
            adapter = new AllOrderAdapter();
            adapter.setNor(isNormalOrder);
            adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    if (isNormalOrder) {
                        jumpToNormalOrder(adapter, position);
                    } else {
                        jumpToAdOrder(adapter, position);
                    }


                }
            });
        }
        recyclerView.setAdapter(adapter);
    }

    private void jumpToNormalOrder(BaseQuickAdapter adapter, int position) {
        AllOrderBean.DataBean bean = ((AllOrderBean.DataBean) adapter.getData().get(position));
        Bundle bundle = new Bundle();
        bundle.putSerializable(ORDERINFO, bean);
        bundle.putBoolean(OrderFinishedActivity.ISNORMALORDER, true);
        Intent intent = new Intent();
        intent.putExtras(bundle);
        if (bean.status == SaleOrderDetailActivity.SALE_FINISHED) {
            $startActivity(OrderFinishedActivity.class, bundle);
        } else if (!bean.exType.equals("0")) {//0.卖出,1.买入
            intent.setClass(mContext, SaleOrderDetailActivity.class);
            startActivityForResult(intent, REQUEST_CODE_UPDATE_INFO);
        } else {
            intent.setClass(mContext, BuyOrderDetailActivity.class);
            startActivityForResult(intent, REQUEST_CODE_UPDATE_INFO);
        }
    }

    private void jumpToAdOrder(BaseQuickAdapter adapter, int position) {
        AllOrderBean.DataBean bean = ((AllOrderBean.DataBean) adapter.getData().get(position));
        Bundle bundle = new Bundle();
        bundle.putSerializable(ORDERINFO, bean);
        bundle.putBoolean(OrderFinishedActivity.ISNORMALORDER, false);
        Intent intent = new Intent();
        intent.putExtras(bundle);
        if (bean.status == AdSaleOrderDetailActivity.SALE_FINISHED) {
            $startActivity(OrderFinishedActivity.class, bundle);
        } else if (!bean.exType.equals("1")) {//0.卖出,1.买入
            intent.setClass(mContext, AdSaleOrderDetailActivity.class);
            startActivityForResult(intent, REQUEST_CODE_UPDATE_INFO);
        } else {
            intent.setClass(mContext, AdBuyOrderDetailActivity.class);
            startActivityForResult(intent, REQUEST_CODE_UPDATE_INFO);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_UPDATE_INFO && resultCode == Activity.RESULT_OK) {
            currentPage = 1;
            if (isNormalOrder) {
                mPresenter.doLoadData(isRefresh, status, currentPage, rows);
            } else {
//                mPresenter.doAdLoadData(isRefresh, status, currentPage, rows);
            }

        }
    }

    /**
     * 只有从交易页面 购买或者卖出 才会执行此方法：只刷新当前 订单状态改变对应的数据，比如： 当订单状态从未付款变为已付款，则更新已付款页面的状态
     *
     * @param refreshOrderListEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(Event.RefreshOrderListEvent refreshOrderListEvent) {
        if (refreshOrderListEvent.getStatues() == status) {
            currentPage = 1;
            if (refreshOrderListEvent.isNor()) {
                mPresenter.doLoadData(isRefresh, status, currentPage, rows);
            } else {
//                mPresenter.doAdLoadData(isRefresh, status, currentPage, rows);
            }

        }
    }



    @Override
    protected void initEvent() {

    }

    @Override
    protected void initView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                isRefresh = false;
                if (isNormalOrder) {
                    mPresenter.doLoadData(isRefresh, status, ++currentPage, rows);
                } else {
//                    mPresenter.doAdLoadData(isRefresh, status, ++currentPage, rows);
                }

            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                isRefresh = true;
                currentPage = 1;
                if (isNormalOrder) {
                    mPresenter.doLoadData(isRefresh, status, currentPage, rows);
                } else {
//                    mPresenter.doAdLoadData(isRefresh, status, currentPage, rows);
                }
            }
        });

        notDataView = getLayoutInflater().inflate(R.layout.empty_view, (ViewGroup) recyclerView.getParent(), false);
        errorView = getLayoutInflater().inflate(R.layout.error_view, (ViewGroup) recyclerView.getParent(), false);
        tvRefresh = errorView.findViewById(R.id.tv_refresh);
        tvRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mRefreshLayout.autoRefresh(0, 10, 1);
            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_order_all;
    }

    @Override
    protected AllOrderPresenter createPresenter() {
        return new AllOrderPresenter(this);
    }

    public static AllOrderFragment getInstance() {
        return instance == null ? new AllOrderFragment() : instance;
    }

    @Override
    public void onSetAdapter(List<AllOrderBean.DataBean> list) {
        if (isRefresh) {
            if (status == 0 || status == 1) {
                postSticky(new Event.RefreshOrderRedEvent(status, isNormalOrder));
            }
            mRefreshLayout.setEnableLoadMore(true);
            if (list != null && list.size() <= 0) {
                adapter.setEmptyView(notDataView);
            }
            adapter.setNewData(list);
        } else {
            if (list == null || list.size() < rows) {
                mRefreshLayout.setEnableLoadMore(false);
            } else {
                mRefreshLayout.setEnableLoadMore(true);
            }
            adapter.addData(list);
        }
    }

    @Override
    public void onShowNoMore() {
        if (mRefreshLayout != null) {
            mRefreshLayout.finishRefresh();
            mRefreshLayout.finishLoadMore();
        }
    }

    @Override
    public void onSetAdAdapter(List<AllOrderBean.DataBean> list) {
        if (isRefresh) {
            if (status == 0 || status == 1) {
                postSticky(new Event.RefreshOrderRedEvent(status, isNormalOrder));
            }
            mRefreshLayout.setEnableLoadMore(true);
            if (list != null && list.size() <= 0) {
                adapter.setEmptyView(notDataView);
            }
            adapter.setNewData(list);
        } else {
            if (list == null || list.size() < rows) {
                mRefreshLayout.setEnableLoadMore(false);
            } else {
                mRefreshLayout.setEnableLoadMore(true);
                adapter.addData(list);
            }

        }
    }

    @Override
    public void onAdShowNoMore() {
        if (mRefreshLayout != null) {
            mRefreshLayout.finishRefresh();
            mRefreshLayout.finishLoadMore();
        }

    }

    public void refreshData(int statu) {
        if (mPresenter != null) {
            if (isNormalOrder) {
                if (isFrist) {
                    isFrist = false;
                } else {
                    this.status = statu;
                    isRefresh = true;
                    currentPage = 1;
                    mPresenter.doLoadData(isRefresh, status, currentPage, rows);
                }
            } else {
//                if (isFrist) {
//                    isFrist = false;
//                } else {
//                    this.status = statu;
//                    isRefresh = true;
//                    currentPage = 1;
//                    mPresenter.doAdLoadData(isRefresh, status, currentPage, rows);
//                }
            }

        }
    }

    @Override
    public void onError(int code) {
        super.onError(code);
        if (isRefresh && adapter != null)
            adapter.setEmptyView(errorView);
    }
}
